package com.myapp.ruyixing.ui.shopmanager;

import static android.view.View.VISIBLE;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.ActivityList;
import com.myapp.ruyixing.model.ActivityList.Act;
import com.myapp.ruyixing.ui.BaseActivity;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.BitmapLruCache;
import com.myapp.ruyixing.utils.LoginHelper;

// 活动管理
public class ActivityManageActivity extends BaseActivity implements
		OnClickListener, OnItemClickListener {
	private List<Act> mList;
	private MyListAdapter mAdapter;
	private ActivityList mDataList;

	private TitleBar mTitleBar;
	private View mLoadingView;
	private ListView mListView;
	private TextView mEmptyView;
	private View mFocusedTabView;
	private EditText mSearchView;

	private RYHttpResponseHandler mHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			try {
				mDataList = (ActivityList) o;
				onLoadingDataFinished(true, mDataList);
			} catch (Exception e) {
				onLoadingDataFinished(false, null);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			onLoadingDataFinished(false, null);
		}
	};

	private void onLoadingDataStarted(String shopbduss, String shopid,
			int status, String title, int pn, int rn) {
		showLoading();
		RYHttpClient.getActivityList(this, mHttpResponseHandler, shopbduss,
				shopid, status + "", title, pn, rn);
	}

	private void onLoadingDataFinished(boolean succeed, ActivityList actList) {
		hideLoading();
		if (succeed && actList != null && actList.items != null) {
			mList.clear();
			mEmptyView.setVisibility(View.GONE);
			mList.addAll(actList.items);
			mAdapter.notifyDataSetChanged();
			if (mList.size() == 0) {
				mEmptyView.setVisibility(VISIBLE);
			}
		} else {
			Toast.makeText(this, "加载失败" + (actList == null ? "" : actList.msg),
					Toast.LENGTH_SHORT).show();
			mEmptyView.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_shop_manager_activity_manage);

		initView();

		mList = new ArrayList<ActivityList.Act>();
		mAdapter = new MyListAdapter();
		mListView.setAdapter(mAdapter);

		onLoadingDataStarted(LoginHelper.getInstance().getShopBduss(),
				LoginHelper.getInstance().getShopId(), 1, "", 0, 50);
	}

	private void initView() {
		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		mLoadingView = findViewById(R.id.my_loading);
		mListView = (ListView) findViewById(android.R.id.list);
		mEmptyView = (TextView) findViewById(android.R.id.empty);
		mListView.setOnItemClickListener(this);

		initTab();

		mTitleBar.setOnIconClickedListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		mSearchView = (EditText) findViewById(R.id.edit_search);
		mSearchView.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				String s = mSearchView.getText().toString();
				s = s.trim();
				ActivityList al = new ActivityList();
				al.items = new ArrayList<ActivityList.Act>();
				if (mDataList != null && mDataList.items != null) {
					for (Act act : mDataList.items) {
						if (act.title != null && act.title.contains(s)) {
							al.items.add(act);
						}
					}
				}
				onLoadingDataFinished(true, al);

				return false;
			}
		});
	}

	private void initTab() {
		mFocusedTabView = findViewById(R.id.about_to_check);
		mFocusedTabView.setOnClickListener(this);
		mFocusedTabView.setSelected(true);

		findViewById(R.id.check_pass).setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.about_to_check:
			if (changeTab(v)) {
				mList.clear();
				mAdapter.notifyDataSetChanged();
				mSearchView.setText("");
				onLoadingDataStarted(LoginHelper.getInstance().getShopBduss(),
						LoginHelper.getInstance().getShopId(), 1, "", 0, 50);
			}
			break;
		case R.id.check_pass:
			if (changeTab(v)) {
				mList.clear();
				mAdapter.notifyDataSetChanged();
				mSearchView.setText("");
				onLoadingDataStarted(LoginHelper.getInstance().getShopBduss(),
						LoginHelper.getInstance().getShopId(), 2, "", 0, 50);
			}

			break;

		default:
			break;
		}
	}

	private void startParticipantManageActivity(String aid) {
		startActivity(new Intent(this, ParticipantManageActivity.class)
				.putExtra("aid", aid));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		startActivity(new Intent(this, ActivityDetailActivity.class).putExtra(
				"aid", mList.get(position).aid));

	}

	private boolean changeTab(View v) {
		if (mFocusedTabView == v) {
			return false;
		}

		mFocusedTabView.setSelected(false);
		mFocusedTabView = v;
		mFocusedTabView.setSelected(true);
		return true;
	}

	private void showTitleBarLoading() {
		mTitleBar.showLoading(true);
	}

	private void hideTitleBarLoading() {
		mTitleBar.showLoading(false);
	}

	private void showLoading() {
		mLoadingView.setVisibility(View.VISIBLE);
	}

	private void hideLoading() {
		mLoadingView.setVisibility(View.GONE);
	}

	private class ViewHolder {
		private TextView mTitleView;
		private NetworkImageView mImageView;
		private TextView mPriceView;
		private TextView mTimeView;
		private TextView mParticipantView;
	}

	private class MyListAdapter extends BaseAdapter {

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;

		public MyListAdapter() {
			super();
			mQueue = Volley.newRequestQueue(ActivityManageActivity.this);
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public int getCount() {
			return mList == null ? 0 : mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(ActivityManageActivity.this)
						.inflate(R.layout.cell_shop_manager_activity_manage,
								parent, false);

				ViewHolder holder = new ViewHolder();
				holder.mTitleView = (TextView) convertView
						.findViewById(R.id.title);
				holder.mImageView = (NetworkImageView) convertView
						.findViewById(R.id.image);
				holder.mTimeView = (TextView) convertView
						.findViewById(R.id.time);
				holder.mPriceView = (TextView) convertView
						.findViewById(R.id.price);
				holder.mParticipantView = (TextView) convertView
						.findViewById(R.id.participants);

				convertView.setTag(holder);
			}
			Act act = mList.get(position);

			ViewHolder mHolder = (ViewHolder) convertView.getTag();

			mHolder.mTimeView.setText("截止时间：" + act.datetime);
			mHolder.mTitleView.setText(act.title);
			mHolder.mParticipantView.setText("参与人数：" + act.num);
			mHolder.mImageView.setImageUrl(act.picurl, mImageLoader);

			final String aid = act.aid;
			mHolder.mParticipantView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startParticipantManageActivity(aid);
				}
			});

			String text = "原价：￥" + act.originalprice + "  现价：￥"
					+ act.presentprice;
			Spannable wordtoSpan = new SpannableString(text);

			int assignStart = text.indexOf("现价：");
			wordtoSpan.setSpan(
					new ForegroundColorSpan(getResources().getColor(
							R.color.text_normal_price)), assignStart + 3,
					text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			mHolder.mPriceView.setText(wordtoSpan);

			return convertView;

		}
	}
}
